package com.shengqiang.cloud.oauth2.service;

import com.shengqiang.cloud.oauth2.model.Client;
import com.shengqiang.cloud.oauth2.model.ResponseMsg;
import com.shengqiang.cloud.oauth2.repository.OAuthClientDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2017/12/10.
 * 客户的管理Service
 */
@Service
public class OAuthClientService {

    @Autowired
    private OAuthClientDao oAuthClientDao;

    /**
     * 注册客户端信息
     *
     * @param client
     * @return
     */
    public ResponseMsg<Client> registerClient(Client client) {
        client.setUid(UUID.randomUUID().toString());
        Client hasClient = oAuthClientDao.queryClient(client.getClientId());
        if (hasClient == null) {
            boolean flag = oAuthClientDao.saveClient(client);
            if (flag) {
                return new ResponseMsg<Client>(1, "success");
            } else {
                return new ResponseMsg<Client>(0, "fail");
            }
        } else {
            ResponseMsg<Client> responseMsg = new ResponseMsg<Client>(2, "该客户端信息已经注册,不必重复注册");
            return responseMsg;
        }
    }

    /**
     * 更新客户端注册信息
     *
     * @return
     */
    public ResponseMsg<Client> updateClient(Client client) {
        Client hashClient = oAuthClientDao.queryClient(client.getClientId());
        if (hashClient == null) {
            return new ResponseMsg<Client>(2, client.getClientId() + ":该客户端未注册,请先进行注册!");
        } else {
            boolean flag = oAuthClientDao.saveClient(client);
            if (flag) {
                return new ResponseMsg<Client>(1, "success");
            } else {
                return new ResponseMsg<Client>(0, "fail");
            }
        }
    }

    /**
     * 查询客户端注册列表
     *
     * @return
     */
    public ResponseMsg<List<Client>> queryClients() {
        List<Client> clients = oAuthClientDao.queryClients();
        if (clients == null) {
            return new ResponseMsg<List<Client>>(0, "fail");
        } else {
            return new ResponseMsg<List<Client>>(1, "success", clients);
        }
    }

    /**
     * 删除注册客户端
     *
     * @param clientId
     * @return
     */
    public ResponseMsg<Client> deleteClient(String clientId) {
        boolean flag = oAuthClientDao.deleteClient(clientId);
        if (flag) {
            return new ResponseMsg<Client>(1, "success");
        } else {
            return new ResponseMsg<Client>(0, "fail");
        }
    }
}
